package com.ruoyi.web.service.impl;

import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.enums.AbnormalEnum;
import com.ruoyi.framework.web.exception.TadpoleException;
import com.ruoyi.web.constant.WalletConstant;
import com.ruoyi.web.domain.AppUser;
import com.ruoyi.web.domain.RechargeRecord;
import com.ruoyi.web.domain.UserJobConfig;
import com.ruoyi.web.domain.UserJobRecord;
import com.ruoyi.web.enums.RechargeRecordEnum;
import com.ruoyi.web.mapper.RechargeRecordMapper;
import com.ruoyi.web.mapper.UserCapitalMapper;
import com.ruoyi.web.mapper.UserJobConfigMapper;
import com.ruoyi.web.mapper.UserJobRecordMapper;
import com.ruoyi.web.service.IAppUserService;
import com.ruoyi.web.service.IUserCapitalService;
import com.ruoyi.web.service.IUserJobRecordService;
import com.ruoyi.web.utils.CommonUtil;
import com.ruoyi.web.utils.IdWorker;
import com.ruoyi.web.utils.MysqlUtil;
import com.ruoyi.web.vo.UserDoJobVO;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 用户任务执行记录Service业务层处理
 *
 * @author ruoyi
 * @date 2023-01-04
 */
@Service
@AllArgsConstructor
public class UserJobRecordServiceImpl implements IUserJobRecordService {
    private final UserJobRecordMapper userJobRecordMapper;
    private final UserJobConfigMapper userJobConfigMapper;
    private final IUserCapitalService capitalService;
    private final UserCapitalMapper capitalMapper;
    private final IdWorker idWorker;
    private final RechargeRecordMapper rechargeRecordMapper;
    private final MysqlUtil mysqlUtil;
    private final IAppUserService appUserService;

    @Override
    public R<String> userDoJob() {
        try {
            mysqlUtil.startLocalTx();
            // 获取用户id
            Long userId = SecurityUtils.getUserId();
            AppUser appUser = appUserService.selectAppUserById(userId);
            if (Objects.isNull(appUser)) {
                CommonUtil.throwError();
            }

            // 获取等级对应配置
            UserJobConfig config = userJobConfigMapper.selectOne(new UserJobConfig() {{
                setLevel(appUser.getVipLevel().longValue());
            }});
            if (config == null) {
                throw new TadpoleException(AbnormalEnum.MSG.UNSUPPORTED_OPERATION.getCode(), "No task execution times, please recharge or invite users to upgrade!");
            }
            // vip0 仅可以体验五天
            if (config.getLevel() == 0) {
                List<Long> longs = userJobRecordMapper.selectDoJobDay(userId);
                if (longs != null && longs.size() >= 5) {
                    throw new TadpoleException(AbnormalEnum.MSG.UNSUPPORTED_OPERATION.getCode(), "Vip0 can only experience 5-day tasks!");
                }
            }
            // 任务执行间隔需大于30min 间隔为固定
            Integer lastJob = userJobRecordMapper.selectLastJob(userId);
            if (lastJob > 0) {
                throw new TadpoleException(AbnormalEnum.MSG.UNSUPPORTED_OPERATION.getCode(), "The task can be executed every 30 minutes, please wait patiently");
            }
            // 获取用户今日执行任务次数
            Date now = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String nowStr = sdf.format(now) + " 00:00:00";
            UserDoJobVO vo = userJobRecordMapper.selectDoJobCount(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(nowStr), userId);
            if (vo.getCount() >= config.getCount()) {
                throw new TadpoleException(AbnormalEnum.MSG.UNSUPPORTED_OPERATION.getCode(), "The number of tasks today has reached the maximum!");
            }
            // 0级会员 20
            if (config.getCondition().compareTo(BigDecimal.ZERO) == 0) {
                config.setCondition(new BigDecimal(20));
            }
            // 获取用户当前资金
//            UserCapital capital = capitalMapper.selectUserCapitalById(userId);
            UserJobRecord record = new UserJobRecord();
            record.setId(idWorker.nextId());
            record.setCreateTime(new Date());
            record.setUserId(userId);
            record.setJobLevel(config.getLevel());
            record.setReward(config.getCondition().multiply(config.getReward()));
            userJobRecordMapper.insertUserJobRecord(record);
            // 充值记录
            RechargeRecord rechargeRecord = new RechargeRecord();
            rechargeRecord.setId(idWorker.nextId());
            rechargeRecord.setUserId(userId);
            rechargeRecord.setCurrency(WalletConstant.USDT);
            rechargeRecord.setType(RechargeRecordEnum.Type.JOB.getValue());
            rechargeRecord.setState(RechargeRecordEnum.Status.SUCCESS.getValue());
            rechargeRecord.setQuantity(config.getCondition().multiply(config.getReward()));
            rechargeRecordMapper.insertRechargeRecord(rechargeRecord);
            capitalMapper.updateUserBalance(config.getCondition().multiply(config.getReward()), userId);
            mysqlUtil.commitLocalTx();
            // 分红
            appUserService.miningDistribution(rechargeRecord, RechargeRecordEnum.Type.RECHARGE_DISTRIBUTION.getValue());
            return R.ok("Successfully executed the task");
        } catch (Exception e) {
            mysqlUtil.rollbackLocalTx();
            return R.fail(e.getMessage());
        }
    }

    /**
     * 查询用户任务执行记录
     *
     * @param id 用户任务执行记录主键
     * @return 用户任务执行记录
     */
    @Override
    public UserJobRecord selectUserJobRecordById(Long id) {
        return userJobRecordMapper.selectUserJobRecordById(id);
    }

    /**
     * 查询用户任务执行记录列表
     *
     * @param userJobRecord 用户任务执行记录
     * @return 用户任务执行记录
     */
    @Override
    public List<UserJobRecord> selectUserJobRecordList(UserJobRecord userJobRecord) {
        return userJobRecordMapper.selectUserJobRecordList(userJobRecord);
    }

    /**
     * 新增用户任务执行记录
     *
     * @param userJobRecord 用户任务执行记录
     * @return 结果
     */
    @Override
    public int insertUserJobRecord(UserJobRecord userJobRecord) {
        userJobRecord.setCreateTime(DateUtils.getNowDate());
        return userJobRecordMapper.insertUserJobRecord(userJobRecord);
    }

    /**
     * 修改用户任务执行记录
     *
     * @param userJobRecord 用户任务执行记录
     * @return 结果
     */
    @Override
    public int updateUserJobRecord(UserJobRecord userJobRecord) {
        userJobRecord.setUpdateTime(DateUtils.getNowDate());
        return userJobRecordMapper.updateUserJobRecord(userJobRecord);
    }

    /**
     * 批量删除用户任务执行记录
     *
     * @param ids 需要删除的用户任务执行记录主键
     * @return 结果
     */
    @Override
    public int deleteUserJobRecordByIds(Long[] ids) {
        return userJobRecordMapper.deleteUserJobRecordByIds(ids);
    }

    /**
     * 删除用户任务执行记录信息
     *
     * @param id 用户任务执行记录主键
     * @return 结果
     */
    @Override
    public int deleteUserJobRecordById(Long id) {
        return userJobRecordMapper.deleteUserJobRecordById(id);
    }
}
